#include "Thread.h"
#include "CurrentThread.h"

#include <semaphore.h>

std::atomic_int Thread::numCreated_(0);

Thread::Thread(ThreadFunc func, const std::string &name)
    : tid_(0)
    , func_(std::move(func))
    , name_(name)
{
    setDefaultName();
}

Thread::~Thread()
{
    thread_->join();
}

void Thread::start()  // 一个Thread对象，记录的就是一个新线程的详细信息
{
    // 开启线程
    thread_ = std::shared_ptr<std::thread>(new std::thread([&](){
        if (isRunning_) {
            perror("Thread is already running\n");
            return;
        }
        isRunning_ = true;
        // 获取线程的tid值
        tid_ = CurrentThread::tid();
        // 开启一个新线程，专门执行该线程函数
        func_(); 
    }));
}
void Thread::setDefaultName()
{
    int num = ++numCreated_;
    if (name_.empty())
    {
        char buf[32] = {0};
        snprintf(buf, sizeof buf, "Thread%d", num);
        name_ = buf;
    }
}